<template>
	<view>
		<view class="avatar-view">
			<u-avatar :src="avatarSrc" mode="aspectFill" shape="circle" size="200rpx" @click="alterAvatar()"></u-avatar>
			<text>点击修改头像</text>
		</view>
		<view class="name-view" @click="nameAlterPopupOpen()">
			<text style="margin-left: 30rpx;font-size: 40rpx;font-weight: bold;">昵称</text>
			<text class="name-text">{{username}}</text>
			<u-icon name="arrow-right" class="u-icon"></u-icon>
		</view>
		<u-popup :show="nameAlterPopup" @close="nameAlterPopupClose()">
			<view class="show-view">
				<view class="popup-top">
					<u-icon name="arrow-left" style="margin-left: 30rpx;" @click="nameAlterPopupClose()"></u-icon>
					<text style="text-align: center;flex: 1;">修改昵称</text>
					<text style="text-align: right;margin-right: 30rpx;" @click="nameAlter()">确认</text>
				</view>
				<u-input
				 style="width: 80%;display: inline-block;margin-right: 2%;"
				placeholder="输入新昵称"
				v-model="newUsername"
				border="bottom"
				autoBlur
				maxlength="10"
				/>
				<view style="display: inline-block;color: #ff6a00;">{{ currentLength }}</view>/10
			</view>
		</u-popup>
		<view class="sex-view">
			<text style="margin-left: 30rpx;font-size: 40rpx;font-weight: bold;">性别</text>
			<view class="choose-view">
				<text v-if="sex==1" class="choose-text">男</text>
				<text v-if="sex==0" class="no-choose-text" @click="changeSex(1)">男</text>
				<text v-if="sex==0" class="choose-text">女</text>
				<text v-if="sex==1" class="no-choose-text" @click="changeSex(0)">女</text>
			</view>
		</view>
		<view class="interest-view">
			<text style="margin-left: 30rpx;font-size: 50rpx;font-weight: bold;">感兴趣</text>
			<view class="interest-show">
				<view class="show-text" @click="interestsAlterPopupOpen()">
					<u-icon name="plus-circle" color="white"></u-icon>
					<text>修改</text>
				</view>
				
				<text v-for="interest in interests" class="show-text">{{interest.tagName}}</text>
			</view>
		</view>
		<u-popup :show="interestsAlterPopup" @close="interestsAlterPopupClose()">
			<view class="show-view">
				<view class="popup-top">
					<u-icon name="arrow-left" style="margin-left: 30rpx;" @click="interestsAlterPopupClose()"></u-icon>
					<text style="text-align: center;flex: 1;">添加兴趣标签</text>
					<text style="text-align: right;margin-right: 30rpx;" @click="interestsAlter()">确认</text>
				</view>
				<view style="margin-bottom: 30rpx;height: 300rpx; overflow-y: auto;">
					<view v-for="newInterest in newInterests" class="new-interests">
						<text>{{newInterest.tagName}}</text>
						<u-icon name="close-circle" @click="deleteInterest(newInterest)"></u-icon>
					</view>
				</view>
				<text style="margin-left: 30rpx;font-weight: bold;">为你推荐</text>
				<view class="choose-new-interests-view">
					<view v-for="chooseInterest in chooseInterests" class="chooseInterests" @click="addInterest(chooseInterest)">
						<text>{{chooseInterest.tagName}}</text>
					</view>
					<!-- <view class="chooseInterests" @click="customInterestPopupOpen()">
						<u-icon name="plus"></u-icon>
					</view> -->
				</view>
				<u-popup :show="customInterestPopup" @close="customInterestPopupClose()" mode="center">
					<view>
						<u-input
						style="margin: 50rpx;padding: 20rpx;"
						placeholder="自定义兴趣标签"
						v-model="customInterest"
						border="bottom"
						autoBlur
						/>
						<text @click="addcustomInterest()" class="custom-btn">确认</text>
						<text @click="customInterestPopupClose()" class="custom-btn">取消</text>
					</view>
				</u-popup>
			</view>
			
		</u-popup>
	</view>
</template>

<script>
	
	
	export default {
		data() {
			return {
				username:'test',
				avatarSrc:'https://img2.baidu.com/it/u=1651919441,2311134258&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1729875600&t=4606142d2ebb86948dca288f8738683e',
				sex:'0',
				interests:[],
				nameAlterPopup:false,
				newUsername:'',
				interestsAlterPopup:false,
				chooseInterests:[],
				newInterests:[],
				customInterestPopup:false,
				customInterest:'',
				uid:'',
				token:'',
			}
		},
		computed: {
		    currentLength() {
		        return this.newUsername.length; // 计算当前字符数
		    }
		},
		methods: {
			initPage(){
				this.uid=uni.getStorageSync('UID');
				this.token=uni.getStorageSync('token');
				//console.log(this.uid);
				if(this.uid!=''&&this.token!=''){
					uni.showLoading({
						title:"loading",
						mask:true
					})
					this.getUsername();
					this.getSex();
					this.getUserAvatar();
					this.getUserInterest();
					uni.hideLoading();
				}else{
					uni.redirectTo({
						url:'/pages/login/login'
					})
					
				}
			},
			getUsername(){
				this.username=uni.getStorageSync('username');
			},
			getSex(){
				this.sex=uni.getStorageSync('sex');
			},
			getUserAvatar(){
				this.avatarSrc=uni.getStorageSync('userAvatar'+this.uid);
			},
			getUserInterest(){
				uni.request({
					url:this.baseUrl+'/getUserInterest',
					method:'POST',
					data:{
						data:{
							userId:this.uid,
						},
						msgType:'getUserInterest'
					},
					header:{
						'Content-Type': 'application/json',
						'token':this.token,
						'uid':this.uid
					},
					success: (res) => {
						console.log(res.data.data);
						if(res.data.code==1){
							this.interests.slice(0,this.interests.length);
							this.interests.length=0;
							for(let i=0;i<res.data.data.length;i++){
								const set={tagId:res.data.data[i].tagId,tagName:res.data.data[i].tagName};
								this.interests.push(set);
							}
						}
					}
				})
			},
			changeSex(sex){
				uni.request({
					url:this.baseUrl+'/setSex',
					method:'POST',
					data:{
						data:{
							userId:this.uid,
							sex:sex
						},
						msgType:'setSex'
					},
					header:{
						'Content-Type': 'application/json',
						'token':this.token,
						'uid':this.uid
					},
					success: (res) => {
						//console.log(res);
						if(res.data.code==1){
							this.sex=sex;
							uni.setStorageSync('sex',sex);
						}
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			nameAlterPopupClose(){
				this.nameAlterPopup=false;
			},
			nameAlterPopupOpen(){
				this.newUsername='';
				this.nameAlterPopup=true;
			},
			nameAlter(){
				if(this.newUsername!=''&&this.newUsername!=this.username){
					uni.request({
						url:this.baseUrl+'/setUsername',
						method:'POST',
						data:{
							data:{
								userId:this.uid,
								newUsername:this.newUsername
							},
							msgType:'setUsername'
						},
						header: {
							'Content-Type': 'application/json',
							'token':this.token,
							'uid':this.uid
						},
						success: (res) => {
							if(res.data.code==1){
								uni.showToast({
									title:res.data.data,
									icon:'success',
									duration:2000
								})
								uni.setStorageSync('username',this.newUsername);
								this.getUsername();
							}
							
						},
						fail(err) {
							
						}
					})
				}
				this.nameAlterPopupClose();
			},
			interestsAlterPopupOpen(){
				this.newInterests=this.interests.slice();
				this.getChooseInterests()
				    .then(() => {
				        if (!this.chooseInterests || !this.interests) {
				            console.error("兴趣数据未正确加载！");
				            return;
				        }
				
				        console.log("初始选择的兴趣:", this.chooseInterests);
				        console.log("兴趣池:", this.interests);
				
				        // 使用 Set 提高查找效率
				        const interestSet = new Set(this.interests.map(item => `${item.tagId}-${item.tagName}`));
				
				        // 过滤出未匹配的兴趣
				        this.chooseInterests = this.chooseInterests.filter(
				            obj => !interestSet.has(`${obj.tagId}-${obj.tagName}`)
				        );
				
				        console.log("过滤后的选择兴趣列表:", this.chooseInterests);
				    })
				    .catch(error => {
				        console.error("处理兴趣时出错:", error);
				    });


				//console.log(this.interests.length);
				
				this.interestsAlterPopup=true;
			},
			interestsAlterPopupClose(){
				this.interestsAlterPopup=false;
			},
			interestsAlter(){
				
				console.log(this.newInterests);
				uni.request({
					url:this.baseUrl+'/interestsAlter',
					method:'POST',
					data:{
						data:{
							userId:this.uid,
							newInterests:this.newInterests
						},
						msgType:'interestsAlter'
					},
					header:{
						'Content-Type': 'application/json',
						'token':this.token,
						'uid':this.uid
					},
					success: (res) => {
						uni.showToast({
							title:res.data.data
						});
						this.interests=this.newInterests.slice();
					}
				})
				this.interestsAlterPopupClose();
			},
			deleteInterest(newInterest){
				let index=this.newInterests.indexOf(newInterest);
				this.newInterests.splice(index,1);
				this.chooseInterests.push(newInterest);
			},
			addInterest(chooseInterest){
				let index=this.chooseInterests.indexOf(chooseInterest);
				this.chooseInterests.splice(index,1);
				this.newInterests.push(chooseInterest);
			},
			customInterestPopupOpen(){
				this.customInterest='';
				this.customInterestPopup=true;
			},
			customInterestPopupClose(){
				this.customInterestPopup=false;
			},
			addcustomInterest(){
				if(this.customInterest!=''){
					this.newInterests.push(this.customInterest);
				}
				this.customInterestPopupClose();
			},
			alterAvatar() {
			    console.log('选取图片');
			    uni.chooseImage({
			        count: 1,
					sizeType:['compressed'],
					crop:{height:100,width:100,resize:false},
			        success: (res) => {
						uni.showLoading({
							title:'上传中',
							mask:true
						})
			            console.log(res);
			            //this.avatarSrc = res.tempFilePaths[0]; // 取第一个图片路径
			            
			            // 上传图片到后端
			            const imgFilePath = res.tempFilePaths[0]; // 获取选中的图片路径
			            
			            // 使用 uni.uploadFile 上传图片
			            uni.uploadFile({
			                url: this.baseUrl+'/img/setAvatar', // 替换为你的接口地址
			                filePath: imgFilePath,
			                name: 'avatar', // 后端接收文件的字段名
			                formData: {
								userId: this.uid, // 示例：附加用户 ID
			                    msgType:'setAvatar'
			                    // 你可以在这里添加更多的字段
			                },
							header:{
								'token':this.token,
								'uid':this.uid
							},
			                success: (uploadRes) => {
			                    console.log(uploadRes);
								const responseData = JSON.parse(uploadRes.data);
								
								console.log(responseData.code);
								if(responseData.code == 1){
									console.log('重新获取头像');
									this.againGetUserAvatar();
									uni.hideLoading();
									uni.showToast({
										title:responseData.data,
										icon:'success',
										duration:2000
									});
								}else{
									uni.hideLoading();
									uni.showToast({
										title:responseData.data,
										icon:'error',
										duration:2000
									});
								}
			                    // 处理上传成功后的逻辑
			                },
			                fail: (error) => {
								uni.hideLoading();
			                    console.error('上传失败', error);
			                }
			            });
			        },
			        fail: (error) => {
			            console.error('选择图片失败', error);
			        }
			    });
			},

			againGetUserAvatar(){
				uni.request({
			        url: this.baseUrl+'/getUserAvatar',
			        method: 'POST',
			        data: {
						data:{
							userId:this.uid
						},
						msgType:'getUserAvatar'
			        },
			        header: {
						'Content-Type': 'application/json',
						'token':this.token,
						'uid':this.uid
			        },
			        success: (res) => {
						console.log(res);
						if(res.data.code==1){
							const userAvatar=res.data.data.imgType+'base64,'+res.data.data.userAvatar;
							this.avatarSrc=userAvatar;
							uni.setStorageSync("userAvatar"+this.uid,userAvatar);
						}
			        },
			        fail: (err) => {
						console.error('请求失败:', err);
			        }
				});
			},
			async getChooseInterests() {
			    return new Promise((resolve, reject) => {
			        uni.request({
			            url: this.baseUrl + '/getChooseInterests',
			            method: 'POST',
			            data: {
			                data: {
			                    userId: this.uid
			                },
			                msgType: 'getChooseInterests'
			            },
			            header: {
			                'Content-Type': 'application/json',
			                'token': this.token,
			                'uid': this.uid
			            },
			            success: (res) => {
			                if (res.data.code == 1) {
			                    // 清空 chooseInterests 以避免重复追加
			                    this.chooseInterests = []; 
			                    for (let i = 0; i < res.data.data.length; i++) {
			                        const set = {
			                            tagId: res.data.data[i].tagId,
			                            tagName: res.data.data[i].tagName
			                        };
			                        this.chooseInterests.push(set);
			                    }
			                    resolve(this.chooseInterests); // 数据加载完成，调用 resolve
			                } else {
			                    reject(new Error(`接口返回错误，code: ${res.data.code}`));
			                }
			            },
			            fail: (error) => {
			                reject(error); // 网络或其他错误
			            }
			        });
			    });
			}

		},
		onShow() {
			this.initPage();
		}
	}
</script>

<style>
.avatar-view {
	text-align: center;
	margin-top: 30rpx;
}
.avatar-view .u-avatar {
	margin: auto;
}
.name-view {
	margin-top: 30rpx;
	display: flex;
	justify-content: space-between; /* 使内容两端对齐 */
	align-items: center; /* 垂直居中 */
	background-color: #fff; /* 背景颜色 */
	border-radius: 10rpx; /* 圆角 */
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 阴影效果 */
	padding: 20rpx;
	margin-left: 20rpx;
	margin-right: 20rpx;
}
.name-view .name-text {
	font-size: 40rpx;
	font-weight: bold;
	flex: 1; /* 使昵称占据剩余空间 */
	text-align: right; /* 左对齐 */
}
.name-view .u-icon {
	margin-left: 10rpx; /* 添加左边距 */
	margin-right: 10rpx;
}
.sex-view {
	margin-top: 30rpx;
	display: flex;
	margin-right: 30rpx;
	justify-content: space-between; /* 使内容两端对齐 */
	align-items: center; /* 垂直居中 */
	background-color: #fff; /* 背景颜色 */
	border-radius: 10rpx; /* 圆角 */
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 阴影效果 */
	padding: 20rpx;
	margin-left: 20rpx;
	margin-right: 20rpx;
}
.sex-view .choose-view {
	flex: 1; /* 使选择区域占据剩余空间 */
	text-align: right; /* 右对齐 */
}
.sex-view .choose-view .choose-text {
	font-size: 40rpx;
	font-weight: bold;
	background-color: #ff6a00;
	color: white; /* 文字颜色 */
	padding: 5rpx 30rpx; /* 添加内边距 */
	border-radius: 15rpx; /* 圆角 */
}
.sex-view .choose-view .no-choose-text {
	font-size: 40rpx;
	font-weight: bold;
	color: #333; /* 默认文字颜色 */
	padding: 5rpx 30rpx; /* 添加内边距 */
	border-radius: 20rpx; /* 圆角 */
}
.interest-view {
	margin-top: 30rpx;
	background-color: #fff; /* 背景颜色 */
	border-radius: 10rpx; /* 圆角 */
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* 阴影效果 */
	padding: 20rpx;
	margin-left: 20rpx;
	margin-right: 20rpx;
}
.interest-view .interest-show {
	margin-top: 30rpx;
	background-color: aliceblue;
	padding: 10rpx; /* 添加内边距 */
	border-radius: 10rpx; /* 圆角 */
}
.interest-view .interest-show .show-text {
	font-size: 35rpx;
	display: inline-flex;
	background-color: #ff6a00;
	color: white; /* 文字颜色 */
	margin: 15rpx; /* 添加外边距 */
	padding: 5rpx 10rpx; /* 添加内边距 */
	border-radius: 10rpx; /* 圆角 */
	white-space: nowrap; /* 不允许文本换行 */
}
.u-popup .show-view{
	height: 1200rpx;
}
.popup-top{
	margin-top: 20rpx;
	margin-bottom: 20rpx;
	display: flex;
}
.u-popup .show-view .choose-new-interests-view{
	margin-top: 20rpx;
	border-radius: 10rpx; /* 圆角 */
	height: 720rpx;
	overflow-y:auto; /* 允许垂直滚动 */
}
.new-interests{
	display: inline-flex;
	margin-top: 20rpx;
	margin-left: 20rpx;
	padding: 10rpx;
	background-color: antiquewhite;
	border-radius: 20rpx; /* 圆角 */
}
.chooseInterests{
	display: inline-flex;
	margin-top: 20rpx;
	margin-left: 20rpx;
	padding: 10rpx;
	background-color: aliceblue;
	border-radius: 20rpx; /* 圆角 */
}
.custom-btn{
	display: inline-flex;
	background-color: aliceblue;
	padding-top: 20rpx;
	padding-bottom: 20rpx;
	width: 50%;
	justify-content: center;
}
</style>
